import { dbConfig } from '@/config/db.config'
import mysql from 'mysql2/promise'

class DatabaseService {
  constructor() {
    this.pool = null
  }

  async connect() {
    if (!this.pool) {
      this.pool = mysql.createPool({
        host: dbConfig.host,
        port: dbConfig.port,
        user: dbConfig.user,
        password: dbConfig.password,
        database: dbConfig.database,
        waitForConnections: true,
        connectionLimit: dbConfig.pool.max,
        queueLimit: 0
      })
    }
    return this.pool
  }

  async query(sql, params) {
    try {
      const connection = await this.connect()
      const [results] = await connection.execute(sql, params)
      return results
    } catch (error) {
      console.error('Database query error:', error)
      throw error
    }
  }

  async transaction(callback) {
    const connection = await this.connect()
    const conn = await connection.getConnection()
    await conn.beginTransaction()

    try {
      const result = await callback(conn)
      await conn.commit()
      return result
    } catch (error) {
      await conn.rollback()
      throw error
    } finally {
      conn.release()
    }
  }
}

export default new DatabaseService() 